﻿using Microsoft.AspNet.Identity;
using Microsoft.AspNet.Identity.Owin;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Threading.Tasks;
using System.Web;
using System.Web.Mvc;
using WebApp.Models;

namespace WebApp.Controllers
{
    [Authorize(Roles = "Administrator")]
    public class UserController : Controller
    {
        private ApplicationUserManager _userManager;

        public UserController()
        {
        }

        public UserController(ApplicationUserManager userManager)
        {
            UserManager = userManager;
        }

        public ApplicationUserManager UserManager
        {
            get
            {
                return _userManager ?? HttpContext.GetOwinContext().GetUserManager<ApplicationUserManager>();
            }
            private set
            {
                _userManager = value;
            }
        }
    
        public async Task<ActionResult> Index()
        {
            var users = UserManager.Users.ToList();
            List<UserViewModel> userVMs = new List<UserViewModel>();
            foreach (var user in users)
            {
                UserViewModel model = new UserViewModel();
                model.Id = user.Id;
                model.Email = user.Email;

                if (user.Roles != null && user.Roles.Count() > 0)
                {
                    var roles = await UserManager.GetRolesAsync(user.Id);
                    var role = roles.FirstOrDefault();
                    //var role = roles.FirstOrDefault(r => r.Id == user.Roles.First().RoleId);
                    if (!string.IsNullOrWhiteSpace(role))
                    {
                        model.Role = role;
                    }
                }
                userVMs.Add(model);
            }
            return View(userVMs);
        }

        [HttpPost, ActionName("ChangeRole")]
        [ValidateAntiForgeryToken]
        public async Task<ActionResult> ChangeRoleConfirmed(string UserId, bool IsMakeAdmin)
        {
            if (ModelState.IsValid)
            {
                if (string.IsNullOrWhiteSpace(UserId))
                {
                    return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
                }

                var user = await UserManager.FindByIdAsync(UserId);
                if (user != null)
                {
                    if (user.Roles != null && user.Roles.Count() > 0)
                    {
                        var roles = await UserManager.GetRolesAsync(UserId);
                        foreach (var item in roles.ToList())
                        {
                            IdentityResult removeRoleResult = await UserManager.RemoveFromRoleAsync(user.Id, item);
                            if (!removeRoleResult.Succeeded)
                            {
                                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
                            }
                        }
                    }
                    IdentityResult addRoleResult = null;
                    if (IsMakeAdmin)
                    {
                        addRoleResult = await UserManager.AddToRoleAsync(UserId, "Administrator");
                    }
                    else
                    {
                        addRoleResult = await UserManager.AddToRoleAsync(UserId, "Manager");
                    }
                    if (!addRoleResult.Succeeded)
                    {
                        return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
                    }
                }
                else
                {
                    return HttpNotFound();
                }
            }
            return RedirectToAction("Index");
        }

        [HttpPost, ActionName("Delete")]
        [ValidateAntiForgeryToken]
        public async Task<ActionResult> DeleteConfirmed(string UserId)
        {
            if (ModelState.IsValid)
            {
                if (string.IsNullOrWhiteSpace(UserId))
                {
                    return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
                }

                var user = await UserManager.FindByIdAsync(UserId);
                if (user != null)
                {
                    if (user.Roles != null && user.Roles.Count() > 0)
                    {
                        var roles = await UserManager.GetRolesAsync(UserId);
                        foreach (var item in roles.ToList())
                        {
                            var roleResult = await UserManager.RemoveFromRoleAsync(user.Id, item);
                            if (!roleResult.Succeeded)
                            {
                                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
                            }
                        }
                    }
                    var userResult = await UserManager.DeleteAsync(user);
                    if (!userResult.Succeeded)
                    {
                        return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
                    }
                }
                else
                {
                    return HttpNotFound();
                }
            }
            return RedirectToAction("Index");
        }

        protected override void Dispose(bool disposing)
        {
            if (disposing)
            {
                if (_userManager != null)
                {
                    _userManager.Dispose();
                    _userManager = null;
                }
            }

            base.Dispose(disposing);
        }
    }
}